package com.kaifamiao.loader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

// 通过 继承 ClassLoader 类集合实现自定义"类加载器"
public class MyClassLoader extends ClassLoader {

    private String path;

    public MyClassLoader(String path) {
        this.path = path;
    }

    @Override
    protected Class<?> findClass(final String name) throws ClassNotFoundException {
        Class<?> c = null;
        System.out.println( "被加载的类名: " + name );
        String pathname = path + '/' + name.replace('.', '/' ) + ".class";
        System.out.println( pathname );
        try {
            // 创建用于读取指定字节码文件的字节输入流
            InputStream in = new FileInputStream(pathname);
            // 读取字节码文件中所有字节
            byte[] bytes = in.readAllBytes();
            in.close();
            // 调用从父类继承的 方法来定义 Class 实例
            c = this.defineClass( name, bytes, 0 , bytes.length );
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
        return c;
    }
}
